import { history } from "@umijs/max";
import React, {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import { Button, Space, Table, TableColumnType } from "antd";
import { preOrderTypes  } from "@/constants/types";
import { fetchIntendedOrderList, intendedOrdertransformOrder } from "../services";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";

interface tabProps {
  searchValue: any;
  activeKey: string;
  tabKey: string,
  refreshNum: Function
}

const statusMaps: any = {
  all: undefined,
  waitOrder: '0',
  ordered: '1',
  canceled: '2'
}

const PreOrderTable = forwardRef(({searchValue = {}, activeKey, tabKey, refreshNum}: tabProps, ref) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0
  });



  const search = async (params:{pageNum: number; pageSize: number} = {
    pageNum: 1,
    pageSize: 10
  }) => {
    const res = await fetchIntendedOrderList({
      ...searchValue,
      ...params,
      status: statusMaps[activeKey]
    });
    setDataSource(res?.data || []);
    setPagination({
      ...params,
      total: res?.total
    });
  }


  const refreshTable = () => {
    if (activeKey !== tabKey) {
      return ;
    }
    search({
      pageNum: 1,
      pageSize: 10
    });
  }
  // 意向单转订单
  const convertToOrder = (record: preOrderTypes) => {
    intendedOrdertransformOrder({id: record?.id}).then(
      res => {
        if (res?.code === '0') {
          history.push(`/order-manage/order-create?preOrderId=${record?.id}`);
        }
      }
    )
  }

  useImperativeHandle(ref, () => ({
    refreshTable
  }));

  useEffect(() => {
    if (tabKey === activeKey) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
    }
  }, [tabKey, activeKey]);

  const fieldColumns: TableColumnType<preOrderTypes> [] = [
    {
      title: '意向单号',
      dataIndex: 'code',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => <XlTableDictColumn value={record?.status} type="preOrderStatusMaps" />
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      width: 180
    },
    {
      title: '预约取货/送仓时间',
      dataIndex: 'appointPickupTime',
      width: 200,
      render: (_, record) => <span>{`${record?.appointPickupDate} ${record?.appointPickupTime}`}</span>
    },
    {
      title: '取货地址',
      dataIndex: 'pickupAddress',
      ellipsis: true,
      width: 300,
      render: (_, record) => {
        if (record?.pickupWay === '1') {
          return <span>{[record?.pickupProvince, record?.pickupCity, record?.pickupArea, record?.pickupAddress].filter(v => !!v).join('')}</span>;
        }
        if (record?.pickupWay === '2') {
          return <span>{record?.cwhName}</span>;
        }
      }
    },
    {
      title: '公司简称',
      dataIndex: 'customerName',
      ellipsis: true,
      width: 150
    },
    {
      title: '下单手机',
      dataIndex: 'mobile',
      width: 150
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100
    },
    {
      title: '国家',
      dataIndex: 'countryName',
      width: 100
    },
    {
      title: '起始地',
      dataIndex: 'sportName',
      width: 100
    },
    {
      title: '目的港',
      dataIndex: 'dportName',
      width: 120
    },
    {
      title: '目的地',
      dataIndex: 'destCode',
      width: 140
    },
    {
      title: '派送方式',
      dataIndex: 'deliveryMethod',
      width: 100
    },
    {
      title: '件数',
      dataIndex: 'totalPieces',
      width: 100
    },
    {
      title: '总体积/CBM',
      dataIndex: 'totalVol',
      width: 120
    },
    {
      title: '总重量/KG',
      dataIndex: 'totalWeight',
      width: 120
    },
    // {
    //   title: '委托单',
    //   dataIndex: '',
    //   width: 100
    // },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      fixed: 'right',
      render: (_, record) => {
       if (String(record?.status) === '0') {
        return (
          <Space>
            <Button type="link" onClick={() => convertToOrder(record)}>去下单</Button>
          </Space>
        );
       }
      }
    },
  ];
 

  const getColumns = () => {
    return fieldColumns;
  }

  return (
    <>
      <Table
         bordered
         rowKey="id"
         dataSource={dataSource}
         columns={getColumns()}
         scroll={{x: calculateTableWidth(getColumns()), y: 610}}
         pagination= {{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            search({pageNum, pageSize});
          }
         }}
      /> 
    </>
  );
});


export default PreOrderTable;